<template>
	<div class="sys-region-container">
		<el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="700px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto">
				<el-row :gutter="35">
					 <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级名称">
							<el-cascader
								:options="regionData"
								:props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
								placeholder="请选择上级名称"
								clearable
								class="w100"
								v-model="state.ruleForm.Pid"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>

					<el-col :span="24" class="mb20">
						<el-radio-group v-model="state.selectedOption">
							<el-radio value="管理处">管理处</el-radio>
							<el-radio value="路段">路段</el-radio>
							<el-radio value="交通量">交通量</el-radio>
							<el-radio value="环境">环境</el-radio>
							<el-radio value="路面结构">路面结构</el-radio>


						</el-radio-group>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.selectedOption === '管理处'" class="mb20">
						<el-form-item label="管理处名称" prop="name" :rules="[{ required: true, message: '管理处名称不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.name" placeholder="管理处名称" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"  class="mb20" v-if="state.selectedOption === '路段'">
						<el-form-item label="路线全称" prop="roadname" :rules="[{ required: true, message: '路线全称不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.roadname" placeholder="路线全称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"v-if="state.selectedOption === '路段'">
						<el-form-item label="路段名称" prop="sectionname" :rules="[{ required: true, message: '路段名称不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.sectionname" placeholder="路段名称" clearable />
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="state.selectedOption === '路段'" class="mb20">
						<el-form-item label="路线编号" prop="roadNo">
							<el-input v-model="state.ruleForm.roadNo" placeholder="路线编号" clearable />
						</el-form-item>
					</el-col>

					<!--  交通量	-->
					<el-col :span="8" v-if="state.selectedOption === '交通量'" class="mb20">
						<el-form-item label="路段名称">
							:{{ state.ruleForm.roadname }}
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="state.selectedOption === '交通量'" class="mb20">
						<el-form-item label="自然车流量">
							:{{ state.trafficDatas.aturalTraffic }}
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="state.selectedOption === '交通量'" class="mb20">
						<el-form-item label="标准车流量">
							:{{ state.trafficDatas.tandardTraffic }}
						</el-form-item>
					</el-col>
					<!--  环境	-->
					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="平均气温">
							:{{ state.envurinmentdatas.verageTemperature }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="最高气温">
							:{{ state.envurinmentdatas.maxTemperature }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="最低气温">
							:{{ state.envurinmentdatas.minTemperature }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="降雨量">
							:{{ state.envurinmentdatas.precipitation }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="环境地质">
							:{{ state.envurinmentdatas.hjdz }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '环境'" class="mb20">
						<el-form-item label="水文地质">
							:{{ state.envurinmentdatas.swdz }}
						</el-form-item>
					</el-col>


					<!--  路面结构	-->
					<el-col :span="24" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="路段名称">
							:{{ state.ruleForm.roadname }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="底基层厚度">
							:{{ state.roadStructures.djchd }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="底基层混合料类型">
							:{{ state.roadStructures.djctype }}
						</el-form-item>
					</el-col>
					<!--  环境	-->
					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="基层厚度">
							:{{ state.roadStructures.jchd }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="基层混合料类型">
							:{{ state.roadStructures.jctype }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="下面层厚度">
							:{{ state.roadStructures.xmchd }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="下面层混合料类型">
							:{{ state.roadStructures.xmctype }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="中面层厚度">
							:{{ state.roadStructures.zmc }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="中面层混合料类型">
							:{{ state.roadStructures.zmctype }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="上面层厚度">
							:{{ state.roadStructures.smc }}
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="state.selectedOption === '路面结构'" class="mb20">
						<el-form-item label="上面层混合料类型">
							:{{ state.roadStructures.smctype }}
						</el-form-item>
					</el-col>

				</el-row>
			</el-form>

			<el-col :span="12" :xs="24">

			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"class="mb20">
				<el-form-item label="检测数据上传" prop="name" :rules="[{ required: true, message: '管理处名称不能为空', trigger: 'blur' }]">
				</el-form-item>
			</el-col>

			<el-col :span="12" class="mb20">
				<el-form-item label="" prop="jcpzd">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(1)" > 上传平整度 </el-button> <br>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jcpzd"   @click="downloadFile(state.jcpzdsrc)" >已入库 | 平整度文档下载 </el-button>
					</template>
				</el-form-item>
			</el-col>

			<el-col :span="12" class="mb20">
				<el-form-item label="" prop="jcps">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(4)" >上传路面破损(分上行,下行两次上传)  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jcpss"   @click="downloadFile(state.jcpsssrc)" >已入库 | 路面破损上行下载 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jcpsx"   @click="downloadFile(state.jcpsxsrc)" >已入库 | 路面破损下行下载 </el-button>

					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="jccz">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(2)" > 上传车辙数据 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jcce"   @click="downloadFile(state.jccesrc)" >已入库 | 车辙数据下载 </el-button>

					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="jspd">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(3)" >上传技术评定明细  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jspd"   @click="downloadFile(state.jspdsrc)" >已入库 | 技术评定下载 </el-button>

					</template>
				</el-form-item>
			</el-col>

			<!-- 上传基础数据EXCL-->
			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"class="mb20">
				<el-form-item label="基础数据上传" prop="name" :rules="[{ required: true, message: '管理处名称不能为空', trigger: 'blur' }]">
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="yhls">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(12)" >路网GPS数据上传(上传注意:必须整条路的GPS数据)  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.yhls"   @click="downloadFile(state.yhlssrc)" >已入库 | 养护历史数据下载 </el-button>
					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="yhls">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(13)" >上传养护历史数据  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.yhls"   @click="downloadFile(state.yhlssrc)" >已入库 | 养护历史数据下载 </el-button>
					</template>
				</el-form-item>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="yhls">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(14)" >上传桥梁桩号  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.yhls"   @click="downloadFile(state.yhlssrc)" >已入库 | 桥梁桩号下载 </el-button>
					</template>
				</el-form-item>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="yhls">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(15)" >上传隧道桩号  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.yhls"   @click="downloadFile(state.yhlssrc)" >已入库 | 隧道桩号下载 </el-button>
					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="sci">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(16)" >上传SCI数据 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.sci"   @click="downloadFile(state.scisrc)" >已入库 | SCI下载 </el-button>
					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="tci">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(17)" >上传TCI数据  </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.tci"   @click="downloadFile(state.tcisrc)" >已入库 | TCI数据下载 </el-button>
					</template>
				</el-form-item>
			</el-col>
			<!--	<MapDragRoute ref="mapDragRoute" :title="地图组件" @handleQuery="handleQuery"  :regionData="state.regionData"/>-->
			</el-col>
			<el-col :span="20" :xs="24" style="display: flex; flex-direction: column">
				<div>
					<table>
						<thead>
						<tr>
							<th>文件名</th>
							<th>下载</th>
						</tr>
						</thead>
						<tbody>
						<tr v-for="file in state.fileListProps" :key="file.name">
							<td>{{ file.fileName }}</td>
							<td><a href="#" @click.prevent="downloadFile(file.url)">下载</a></td>
						</tr>
						</tbody>
					</table>
				</div>
			</el-col>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action="" :on-change="handleChange" accept=".GPS,.jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="sysEditRegion">
import { reactive, ref } from 'vue';
import {ElMessage, UploadInstance} from 'element-plus';
import { getAPI } from '/@/utils/axios-utils';
import {SysFileApi, SysRegionApi} from '/@/api-services/api';
import {SysFile, UpdateRegionInput} from '/@/api-services/models';
import MapDragRoute from '/@/views/map/MapDragRoute.vue';
import {uploadFilesPoject} from "/@/api/region/region";
import {addRoaddisinfo, detailRoaddisinfo, updateRoaddisinfo} from "/@/api/main/roaddisinfo";
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import { downloadByUrl } from '/@/utils/download';

const editRegionRef = ref<InstanceType<typeof MapDragRoute>>();

const props = defineProps({
	title: String,
	row: {
		type: Object,
		required: true
	},
	regionData: {
		type: Array,
		required: true,
	},
	year: {
		type: String,
		required: true
	},
	pid: {
		type: String,
		required: true
	},
});
const emits = defineEmits(['handleQuery']);
const ruleFormRef = ref();
const ruleForm = ref<any>({});
const uploadRef = ref<UploadInstance>();
const state = reactive({
	fileData: [] as Array<SysFile>,
	selectedOption:"",
	fileList: [] as any,
	fileName: '',
	key:0,
	Pid : undefined,
	year : undefined,
	isShowDialog: false,
	dialogUploadVisible: false,
	fileListProps: [] as any,
	envurinmentdatas: [] as any,
	trafficDatas: [] as any,
	roadStructures: [] as any,

	ruleForm: {} as UpdateRegionInput,
	regionData:[],
	lmjzinfo:'',
	lmjzinfosrc:"",

	jcpzd:'',
	jcpzdsrc:'',
	jcce:"",
	jccesrc:'',
	jcjspd:'',
	jcjspdsrc:'',
	jcpss:'',
	jcpsssrc:'',
	jcpsx:'',
	jcpsxsrc:'',

	dialogDocxVisible: false,
	dialogXlsxVisible: false,
	dialogPdfVisible: false,
	showViewer: false,
	docxUrl: '',
	excelUrl: '',
	pdfUrl: '',
});


// 打开上传页面
const openUploadDialog = (key: any)=> {
	state.fileList = [];
	state.Pid=props.row.id;
	state.key=key;
	if(props.year) {
		// 如果 props.year 有值，则使用 props.year
		state.year = props.year;
	} else {
		// 如果 props.year 为 null 或 undefined，则设置默认的当前时间年度
		const currentDate = new Date();
		state.year = currentDate.getFullYear()
	}
	console.log('传递过来参数属性',props.row)
	state.dialogUploadVisible = true;

};

// 下载
const downloadFile = async (url: any) => {
	downloadByUrl({ url: url });
};

// 打开文件预览页面
const openFilePreviewDialog = async (row: any) => {
	if (row.suffix == '.pdf') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.pdfUrl = getFileUrl(row);
		state.dialogPdfVisible = true;
	} else if (row.suffix == '.docx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.docxUrl = getFileUrl(row);
		state.dialogDocxVisible = true;
	} else if (row.suffix == '.xlsx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.excelUrl = getFileUrl(row);
		state.dialogXlsxVisible = true;
	} else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex((e) => e == row.suffix) > -1) {
		state.previewList = [getFileUrl(row)];
		state.showViewer = true;
	} else {
		ElMessage.error('此文件格式不支持预览');
	}
};


// 获取文件地址
const getFileUrl = (row: SysFile): string => {
	if (row.bucketName == 'Local') {
		return `/${row.filePath}/${row.id}${row.suffix}`;
	} else {
		return row.url!;
	}
};

// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	state.fileList = fileList;
};



// 上传
const uploadFile = async () => {
	const params = new FormData();

	if (state.fileList.length >=1){
		for (let i = 0; i < state.fileList.length; i++) {
			state.fileList[i].pid = state.Pid;
			console.log('fileList:', state.fileList[i]);
			const filename= state.fileList[i].raw.name;

			params.append('files', state.fileList[i].raw);
		}

		params.append('pid',state.Pid);
		params.append('year',state.year);
		params.append('key',state.key);
		const fileInfoResponse	= await uploadFilesPoject(params);
		console.log('img id', fileInfoResponse.data.result[0].id);
		console.log('img url', fileInfoResponse.data.result[0].url);
		if(fileInfoResponse.data.type==='success'){
			ElMessage.success('上传成功')
			state.dialogUploadVisible = false;
		}
		handleFileInfoResponse(fileInfoResponse);
	}
	state.key=0;
	state.Pid=0;
	state.dialogUploadVisible = false;
};



const handleFileInfoResponse = (fileInfoResponse) => {
	// 根据 key 值进行判断和赋值
	console.log('key', state.key);

	switch (state.key) {
		case 1:
			state.jcpzd = fileInfoResponse.data.result[0].id;
			state.jcpzdsrc = fileInfoResponse.data.result[0].url;
			console.log('平整度excl', state.jcpzdsrc );
			break;
		case 2:
			state.jcce = fileInfoResponse.data.result[0].id;
			state.jccesrc = fileInfoResponse.data.result[0].url;
			break;
		case 3:
			state.jcjspd = fileInfoResponse.data.result[0].id;
			state.jcjspdsrc = fileInfoResponse.data.result[0].url;
			break;
		case 4:
			state.jcpss = fileInfoResponse.data.result[0].id;
			state.jcpsssrc = fileInfoResponse.data.result[0].url;
			break;
		case 5:
			state.jcpsx = fileInfoResponse.data.result[0].id;
			state.jcpsxsrc = fileInfoResponse.data.result[0].url;
			break;
		default:
			break;
	}
};


// 打开弹窗
const openDialog = async (row: any) => {
	console.log('Saving with pid:', props.pid);
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
	state.ruleForm = JSON.parse(JSON.stringify(row));
	state.fileListProps=props.row.files;
	state.envurinmentdatas=row.envurinmentdatas[0];
	state.trafficDatas=row.trafficDatas[0];
	state.roadStructures=row.roadStructures[0];


	state.fileListProps.forEach(file => {
		if (file.key === '1') {
			state.jcpzd = file.id;
			state.jcpzdsrc = file.url;
			console.log('文件ID',state.jcpzd)
			console.log('文件url',state.jcpzdsrc)
		} else if (file.key === '2') {
			state.sypd = file.id;
			state.sypdsrc = file.url;
		} else if (file.key === '3') {
			state.czzd = file.id;
			state.czzdsrc = file.url;
		} else if (file.key === '4') {
			state.jctjzk = file.id;
			state.jctjzksrc = file.url;
		} else if (file.key === '5') {
			state.xyb = file.id;
			state.xybsrc = file.url;
		}
	});
	state.isShowDialog = true;
	ruleFormRef.value?.resetFields();


	//	state.leidaimage = ruleForm.value.leidaimage;
	//	state.leidaimagesrc = ruleForm.value.leidaimagesrc;

};

// 关闭弹窗
const closeDialog = () => {
	emits('handleQuery');
	state.isShowDialog = false;

};

// 取消
const cancel = () => {
	state.fileList = [];
	state.isShowDialog = false;
};

// 提交
const submit = () => {

	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = ruleForm.value;
			values.pid = props.pid;
			values.year = props.year;
			//检测数据上传
			values.jcpzd = state.jcpzd;
			values.jcpzdsrc = state.jcpzdsrc;

			values.leidaimage = state.lmjzinfo;
			values.leidaimagesrc = state.lmjzinfosrc;

			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
				await getAPI(SysRegionApi).apiSysRegionAddPost(values);
			} else {
				await getAPI(SysRegionApi).apiSysRegionUpdatePost(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});




};
// 文件渲染完成
const renderedHandler = () => {};
// 文件渲染失败
const errorHandler = () => {};
// 导出对象
defineExpose({ openDialog });
</script>
